/*
 * @Author: ShiJunJie
 * @Date: 2022-04-01 14:33:50
 * @LastEditors  : ShiJunJie
 * @LastEditTime : 2022-05-09 11:18:34
 * @Descripttion: 
 */
import type { Router } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import storage from 'good-storage'
import { setupLayouts } from 'virtual:generated-layouts'


import NotFound from "@/components/exception/[...404].vue";
import HomePage from "@/views/async/home/index.vue";

import NProgress from 'nprogress'
NProgress.configure({ speed: 500, showSpinner: false })

import 'nprogress/nprogress.css'
import { editorAllObject } from '@/utils/util';
import { escapeStr } from '@/stores/routerNameMap';

const REDIRECT_NAME = 'Redirect';

interface RouteConst {
  /** 路由名称 */
  name: String;
  /** 路由路径 */
  path: string;
  /** 路由标题 */
  title: string;
}

// reset router
export function resetRouter(router: Router) {
  const resetWhiteNameList = ['Login', REDIRECT_NAME];
  router.getRoutes().forEach((route) => {
    const { name } = route;
    if (name && !resetWhiteNameList.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name);
    }
  });
}
/** 路由name转义 */
export function createRoutes(routes: RouteRecordRaw[]): RouteRecordRaw[] {
  routes.push({ path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound, meta: { layout: "blank" } });
  // routes.push({ path: '/admin/home', name: '工作台', component: HomePage, meta: { layout: "BasicLayout", requiresAuth: true } });
  editorAllObject(routes, (e: RouteRecordRaw) => {
    e.name = escapeStr(e.name || e.path)
    // console.log('routes', e);
  })
  return setupLayouts(routes);
}

export async function createGuard(router: Router) {

  router.beforeEach(async (to: any, from: any, next: any) => {
    // window.$loadingBar?.start();
    NProgress.start()
    document.title = `${import.meta.env.VITE_APP_NAME} ${to.meta.title || to.name}`
    console.log('路由监听', `from:${from.path}`, `to:${to.path}`, to)

    //在跳转路由之前，先清除所有的请求(结合axios使用)
    // clearPending();

    const needLogin = Boolean(!to.meta?.requiresAuth) //requiresAuth为真时反而不需要鉴权？
    // 此路由需要授权，请检查是否已登录
    if (to.path === '/login' && storage.get('USER_TOKEN')) {
      return next({ path: '/' })
    }
    if (needLogin && !storage.get('USER_TOKEN')) {
      console.log('此路由需要授权，请检查是否已登录')
      return next({ path: '/login', query: { redirect: to.fullPath } })
    } else {

    }

    next();
  })

  router.afterEach((to: any, from: any, fail: any) => {
    NProgress.done() // NProgress结束进度条
    // if (fail) {
    // } else {
    // }
  })

  router.onError((error: any) => {
    NProgress.done()
    console.log('路由错误', error);
  });
}
